#/bin/bash

mountPoint=$(mount -t orcafs | head -1 | awk '{print $3}')
persent=9 # usedsize 超出 hardlimit 的百分数 ，实际为 persent * 10 / 100
workdir="/root/hzz"

# 临时文件，使用前先删除
TmpFile="${workdir}/tmp/quota.tmp"
ListQuotaFile="${workdir}/tmp/quota.list"
NeedResetFile="${workdir}/tmp/reset.list"
ExecFlagFile="${workdir}/tmp/run.setquota"

# 日志文件
ResetLogFile="${workdir}/log/setquota.log"

# 读取需要重新设置配额的文件，依次使用 du 命令获取当前准确大小，然后重置配额
function resetQuota()
{
	if [ $# -ne 1 ]; then echo "Error: parameter 1 should be quota path."; exit 1; fi

	quotaDir=$1
	dirPath=${mountPoint}${quotaDir}

	if [ ! -d ${dirPath} ]; then echo "Error: ${dirPath} is not exist or not a directory"; exit 1; fi
	#echo "QuotaDir: ${dirPath}"

	quotaNum=$(orcafs-ctl --listquota --dir=${quotaDir} | grep DIR | wc -l)
	if [ ${quotaNum} -ne 1 ]; then echo "Error: ${quotaDir} has not one quota (${quotaNum})"; exit 1; fi

	oldID=$(orcafs-ctl --listquota --dir=${quotaDir} | grep DIR | awk -F'|' '{print $2}'| awk '{print $1}')
	quotaType=$(orcafs-ctl --listquota --dir=${quotaDir} | grep DIR | awk -F'|' '{print $1}'| awk '{print $1}')
	if [ "${quotaType}"X == "DIR"X ]; then
		setID="";
	elif [ "${quotaType}"X == "DIR_UID"X ]; then
		setID=" --uid=${oldID} ";
	elif [ "${quotaType}"X == "DIR_GID"X ]; then
		setID=" --gid=${oldID} ";
	fi

	hardLimit=$(orcafs-ctl --listquota --dir=${quotaDir} | grep DIR | awk -F'|' '{print $3}'| awk '{print $1}')
	softLimit=$(orcafs-ctl --listquota --dir=${quotaDir} | grep DIR | awk -F'|' '{print $4}'| awk '{print $1}')
	
    used=$(orcafs-ctl --listquota -h --dir=${quotaDir} | grep DIR | awk -F'|' '{print $5}'| awk '{print $1}')
	usedBytes=$(orcafs-ctl --listquota --dir=${quotaDir} | grep DIR | awk -F'|' '{print $5}'| awk '{print $1}')
	
    echo ">> $(date +%H:%M:%S) : ${quotaDir} quotaUsed:${used}/${usedBytes}" >> ${ResetLogFile}
	duSize=$(du -sb ${dirPath} | tail -1 | awk '{print $1}')

    # 执行设置配额命令
	cmdStr="orcafs-ctl --setquota --hardlimit=${hardLimit} --softlimit=${softLimit} ${setID} --dir=${dirPath} --usedsize=${duSize} --force"
	echo "${cmdStr}" >> ${ResetLogFile}
	${cmdStr}

    # 记录统计信息
    if (( ${usedBytes} >  ${duSize})); then
        diffByte=$((${usedBytes} - ${duSize}))
    else
        diffByte=$((${duSize} - ${usedBytes}))
    fi
    diffGiga=$( echo "scale=2; ${diffByte}/1024/1024/1024" | bc -l)
    printf "Result: set quotasize(%-15d) to dusize(%-15d), diff(%-15d Bytes/%-10d GB)\n" ${usedBytes} ${duSize} ${diffGiga} >> ${ResetLogFile}
}

# 获取所有配额列表，筛选出已使用容量超出硬阈值的 90% 的配额目录，排序后保存到文件，后续使用
function getResetList()
{
	rm -f ${TmpFile}
	rm -f ${ListQuotaFile}
	rm -f ${NeedResetFile}
	orcafs-ctl --listquota | grep DIR | awk -F'|' '{print $6" "$3" "$5}' | awk '{print $1" "$2" "$3}' > ${ListQuotaFile}

	cat ${ListQuotaFile} | while read dir hardlimit usedsize
        do
		if [ ${hardlimit} -eq 0 ]; then
			# echo "hard=${hardlimit} used=${usedsize} dir=${dir}"
			continue
		fi

		resetLimit=$[ ${hardlimit} * ${persent} / 10 ] # 已使用容量超出硬阈值的 90%，则需要校准
		if [ ${usedsize} -gt ${resetLimit} ]; then
			printf "%-15d   %-15d   %s\n" $hardlimit $usedsize $dir >> ${TmpFile}
			#printf "%-15d   %-15d   %s\n" $hardlimit $usedsize $dir >> ${NeedResetFile}
		fi
        done

	sort -k2,2n ${TmpFile} > ${NeedResetFile}
}

# 同一时间只能有一个脚本再执行，此文件存在时说明脚本正在执行，输出报错信息并退出
if [ -f ${ExecFlagFile} ]; then
	echo -e "\n====== Date: $(date) : Is running, exit =====\n" >> ${ResetLogFile}
	echo "Is running, exit!"
	exit
else
    echo "running" > ${ExecFlagFile}
fi

getResetList
num=$(cat ${NeedResetFile} | wc -l)
echo -e "\n====== Date: $(date) : will reset ${num} quota =====\n" >> ${ResetLogFile}

cur=0
cat ${NeedResetFile} | while read hard uesd dir
do
	resetQuota ${dir}
	cur=$((${cur}+1))
    echo -e "Completion progress: ${cur}/${num}" >> ${ResetLogFile}
done

# 成功执行后删除 flag 文件，手动执行脚本且中途使用 ctrl-c 退出时要手动删除 falg 文件
rm -f ${ExecFlagFile}